<template>
	<view class="" :onShareAppMessage="state.shareInfo">
		<su-sticky bgColor="#fff">
			<su-tabs :list="state.tabs" lineColor="#F52F1F" @change="changeTab" :current="state.activeTab"></su-tabs>
		</su-sticky>
		<!-- <view class="aliasname-title" v-if="state.activeTab == 0">
			{{state.categoryList[0]?.aliasname}}
		</view> -->
    <s-empty v-if="state.categoryGoodList.length === 0" icon="/static/soldout-empty.png" text="暂无商品">
    </s-empty>
		<view class="c-goods-list" v-else>
			<view v-for="item in state.categoryGoodList" :key="item.id">
				<s-goods-column-seckill class="" size="md" :data="item" :grouponTag="true"
					:goodsFields="state.goodsFields" :topRadius="5" :bottomRadius="5" @addCarClick="addCarClick" @shareTap="shareTap" @click="
				      sheep.$router.go('/pages/goods/index', {
				        id: item.id,
				      })
				    ">
          <!-- <template v-slot:cart></template> -->
				</s-goods-column-seckill>
			</view>
		</view>

		<view class="" v-if="state.activeTab == 0" v-for="item in state.promotList" :key="item.id">
			<view class="aliasname-title">
				{{item.name}}
			</view>
			<view class="c-goods-list">
				<view v-for="(item2,index2) in item.children" :key="item.id">
					<s-goods-column class="" size="md" :data="item2" :grouponTag="true" :goodsFields="state.goodsFields"
						:topRadius="5" :bottomRadius="5" @click="
					      sheep.$router.go('/pages/goods/index', {
					        id: item2.id,
					      })
					    ">
						<template v-slot:cart>
							<view class="bottom-operate">
								<button open-type="share" :data-row="item2" class="icon-button" @tap.stop="share">
									<uni-icons type="redo" size="20" color="#8e8e8e"></uni-icons>
								</button>
								<view class="icon-button" @tap.stop="poster(item2)">
									<uni-icons type="image" size="20" color="#8e8e8e"></uni-icons>
								</view>
								<view class="icon-button" @tap.stop="link(item2.id)">
									<uni-icons type="paperclip" size="20" color="#8e8e8e"></uni-icons>
								</view>
								<view class="icon-button cart-button">
									<uni-icons type="cart" size="20" color="#fff"></uni-icons>
								</view>
							</view>
						</template>
					</s-goods-column>
				</view>
			</view>
		</view>
		<!-- 规格与数量弹框 -->
		<view class="detail-swiper-selector" v-if="state.goodsInfo.id">
			<s-select-sku
				:goodsInfo="state.goodsInfo" :show="state.showSelectSku" @addCart="onAddCart" @buy="onBuy"
				@change="onSkuChange" @close="state.showSelectSku = false" />
		</view>
		<!-- 分享海报 -->
		<canvas-poster ref="SharePosterRef" :show="state.showPosterModal" :shareInfo="state.shareInfo"
			@close="state.showPosterModal = false" />
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		unref,
		nextTick
	} from 'vue';
	import {
		onShow,
		onHide,
		onLoad,
		// onShareAppMessage
	} from "@dcloudio/uni-app"
	import sheep from '@/sheep';
	import canvasPoster from '@/sheep/components/s-share-modal/canvas-poster/index.vue';
	const SharePosterRef = ref('SharePosterRef');
	import {
		showShareModal
	} from '@/sheep/hooks/useModal';
	const emits = defineEmits(['updateShareInfo']);
	
	const state = reactive({
		activeTab: 0,
		tabs: [],
		categoryList: [],
		promotList: [],
		categoryGoodList: [],
		goodsFields: {
			title: {
				show: true,
			},
			subtitle: {
				show: true,
			},
			price: {
				show: true,
			},
			original_price: {
				show: true,
			},
			sales: {
				show: false,
			},
			stock: {
				show: false,
			},
		},
		shareInfo: {},
		showPosterModal: false, //海报弹窗
		showSelectSku: false, //加入购物车
		goodsInfo: {}
	})

	async function getCategoryList() {
		const res = await sheep.$api.custom.categoryList()
    if (res.code !== 1) return;
		state.categoryList = res.data
		state.tabs = res.data.map(item => {
			return {
				name: item.name,
			}
		})
		state.categoryGoodList = res.data[0].children
	}

	async function getPromotList() {
		const res = await sheep.$api.custom.promotList()
		state.promotList = res.data
	}
	/**
	 * @添加购物车
	 */
	function addCarClick(item) {
    state.goodsInfo = {};
		// console.log(item.id, '添加购物车')
		sheep.$api.goods.detail(item.id).then((res) => {
			if (res.code === 1) {
				state.goodsInfo = res.data;
				// state.goodsSwiper = formatGoodsSwiper(state.goodsInfo.images);
				// state.type = getGoodsType(state.goodsInfo.isxh);
				// state.goodsInfo.status = [{
				// 	title: state.type.name,
				// 	content: state.type.name + '商品'
				// }];
				// nextTick(() =>{
					state.showSelectSku = true
					// console.log(155)
				// })

				// console.log(state.goodsInfo,'154')
			} else {
				// 未找到商品
				state.goodsInfo = null;
			}
		});
	}
	function shareTap(shareInfo){
		emits('updateShareInfo',shareInfo)
	}
	// 规格变更
	function onSkuChange(e) {
		state.selectedSkuPrice = e;
	}

	// 添加购物车
	function onAddCart(e) {
		sheep.$store('cart').add(e);
    state.showSelectSku = false
	}

	// 立即购买
	function onBuy(e) {
		sheep.$router.go('/pages/order/confirm', {
			data: JSON.stringify({
				order_type: 'goods',
				goods_list: [{
					goods_id: e.goods_id,
					goods_num: e.goods_num,
					goods_sku_price_id: e.id,
				}, ],
			}),
		});
    state.showSelectSku = false
	}

	function changeTab(value) {
    state.categoryGoodList = []
		console.log('当前选中的项：', value)
		state.activeTab = value.index
		state.categoryGoodList = state.categoryList[value.index].children
    console.log(state.categoryGoodList.length)
	}

	// onShareAppMessage((res) => {
	// 	console.log(res,'res')
	// 	if (res.from == 'button') {
	// 		const info = res.target.dataset.row
	// 		return {
	// 			title: info.title, //分享标题
	// 			path: "/pages/goods/index?id=" + info.id, //分享链接
	// 			imageUrl: info.image
	// 		}
	// 	}
	// })

	function share() {}

	async function poster(row) {
		state.shareInfo =
			await sheep.$platform.share.getShareInfo({
				title: row.title,
				image: sheep.$url.cdn(row.image),
				desc: row.subtitle,
				params: {
					page: '2',
					query: row.id,
				},
			}, {
				type: 'goods', // 商品海报
				title: row.title, // 商品标题
				image: sheep.$url.cdn(row.image), // 商品主图
				price: row.price, // 商品价格
				original_price: row.original_price, // 商品原价
			}, );
		setTimeout(() => {
			unref(SharePosterRef).getPoster();
			state.showPosterModal = true;
		}, 500);

	}

	async function link(id) {
		uni.showToast({
			title: '小程序正式发布后才能使用哦~',
			icon: "none",
			duration: 2000
		});
		return
		let params = {
			page_url: '/pages/goods/index?id=' + id,
		}
		const url = await getAppLink(params)
		console.log('返回的url：', url);
	}

	async function getAppLink(params) {
		// AppID(小程序ID)
		// const appid = ''
		// AppSecret(小程序密钥)
		// const secret = ''
		// 先发起请求获取凭证
		await uni.request({
			url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`,
			method: 'GET',
			success(res) {
				console.log('获取凭证', res);
				// 再发起请求获取url
				uni.request({
					url: `https://api.weixin.qq.com/wxa/genwxashortlink?access_token=${res.data.access_token}`,
					method: 'POST',
					data: {
						...params
					},
					success(result) {
						console.log('生成网址：', result.data);
						return result.data.link
					}
				})
			}
		})
	}

	onLoad(() => {
		getCategoryList()
		getPromotList()
	})
</script>

<style lang="scss" scoped>
	.c-goods-list {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 10rpx;

		>view {
			box-sizing: border-box;
			width: 50%;
			padding: 10rpx;
		}
	}

	.aliasname-title {
		position: relative;
		color: rgb(38, 38, 38);
		font-size: 32rpx;
		text-align: left;
		font-weight: 500;
		padding: 30rpx 0;
		padding-left: 45rpx;

		&::before {
			position: absolute;
			left: 20rpx;
			top: 50%;
			transform: translateY(-50%);
			content: "";
			width: 14rpx;
			height: 55rpx;
			border-radius: 8rpx;
			background-color: #F52F1F;
		}
	}

	.bottom-operate {
		border-top: 1px solid #d9d9d9;
		margin: 0 10rpx;
		display: flex;
		justify-content: space-between;
		padding: 10rpx 0;

		.icon-button {
			width: 66rpx;
			height: 50rpx;
			background-color: #f0f0f0;
			text-align: center;
			line-height: 50rpx;
			border-radius: 40rpx;
			margin: 0;
			padding: 0;

			&::after {
				border: 0;
			}
		}

		.cart-button {
			background: linear-gradient(135deg, #F78840, #F3373F);
		}
	}
</style>
